<?php
/**
 * 将离线订单同步到mysql
 */
class Order_offline_sync extends Bg_Controller{
	
	public function __construct() {
		parent::__construct ();
		$this->load->model('User_order_mdl','order');
		$this->load->model('Order_sync_queue_mdl','syncQueue');
		$this->load->model('Order_offline_sync_queue_mdl','offlineSyncQueue');
		$this->load->model('Order_offline_sync_log_mdl','offlineSyncLog');
	}
	
	/**
	 * 同步离线订单
	 */
	public function run(){
		for ( $i=0;$i<30;$i++ ){
			try {
				$this->syncOrder();
			}catch (\Exception $e){
				echo $e->getMessage();
			}
			sleep(1);
		}
	}
	
	/**
	 * 将mongo队列中订单同步到mysql中
	 */
	protected  function syncOrder(){
		
		$orders = $this->offlineSyncQueue->dequeue();
		
		if ( !empty($orders) ){
			
			foreach ($orders as $order){
				
				$time = time();
				$_id = $order['_id'];
				unset($order['_id']);
				
				//将该信息更新为正在操作
				$up = $this->offlineSyncQueue->up($_id);
				
				if ( !empty($order['odetail']) && is_array($order['odetail']) && $up ){
					
					foreach ($order['odetail'] as $v){
						$orderID = $this->order->bginsert($v);
					    if( empty($orderID) ) continue;
						// 记录到缓存队列
					    $this->syncQueue->enqueue($orderID,$v['userID']);
					}
					
				}
				
				//处理完后
				$order['state'] = 2;
				$order['utime'] = $time;
				
				//将数据备份
				$bakLog = $this->offlineSyncLog->insert($order);
				//处理完清除队列
				$finish = $this->offlineSyncQueue->clean($_id);
				
			}
			
		}
		
	}
	
	
}